<?php


namespace PKApp\Attachment;


use PKApp\Attachment\Classes\AttachmentCtrl;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\JSON;
use PKFrame\DataHandler\Numbers;

class AdminUploadByUEditor extends AttachmentCtrl
{

    public function Main()
    {
        switch (request()->get('action')) {
            case 'config':
                $path = path_app(request()->module()) . 'Data' . DS . 'UEditor.json';
                file_exists($path) ?: $this->noticeByJson('UEditor Config file no exists');
                $result = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($path)), true);
                $result['imageUrlPrefix'] = '//' . request()->host() . '/';
                $this->outByUEditor($result);
                break;
            case 'uploadimage':
                $this->accept = 'images';
                $this->pathUrl = date('Ymd');
                $params = $this->upload();
                fileHelper()->Uploaded($this->uploadFile_nameTmp,
                    $this->diskOfPath() . DS, $this->save_fileName);
                $this->serviceOfUpload()->Add($params);
                $this->outByUEditor(["state" => "SUCCESS", "url" => $params['url'], 'title' => $this->save_fileName,
                    "original" => $params['fileName'], "type" => $this->uploadFile_type, 'size' => $this->uploadFile_size]);
                break;
            case 'listimage':
                $this->outByUEditor($this->listImage());
                break;
            case 'catchimage':
                // 远程图片
                $this->catchImage();
                break;
            case 'uploadscrawl':
            case 'uploadvideo':
            case 'uploadfile':
            default:
                break;
        }
    }

    protected function catchImage()
    {
        $list_source = request()->post('source');
        $list_json = [];
        if (Arrays::Is($list_source)) {
            $list_db = [];
            foreach ($list_source as $item_url) {
                $this->url_img = $item_url;
                $this->checkReqOfPicUrl();
                $info = array_merge(['fileName' => $this->getImageNameOfUrl(), 'fileType' => 'images',
                    'createTime' => TIMESTAMP, 'updateTime' => TIMESTAMP,], $this->saveRemoteImg());
                $list_db[] = $info;
                $list_json[] = [
                    "state" => 'SUCCESS',
                    "url" => $info["url"],
                    "size" => $info["size"],
                    "title" => htmlspecialchars($info["fileName"]),
                    "original" => htmlspecialchars($info["fileName"]),
                    "source" => htmlspecialchars($item_url)
                ];
            }
            $this->serviceOfUpload()->BatchInsert($list_db);
        }
        $this->outByUEditor([
            'state' => count($list_json) ? 'SUCCESS' : 'ERROR',
            'list' => $list_json
        ]);
    }

    protected function listImage(): array
    {
        $size = Numbers::To(request()->get('size'));
        $start = Numbers::To(request()->get('start'));
        $allowFiles = substr(str_replace(".", "|", join("",
            [".png", ".jpg", ".jpeg", ".gif"])), 1);
        $files = $this->_getFiles($this->diskOfPath(), $allowFiles);
        $count_files = count($files);
        if ($count_files == 0) {
            return [
                "state" => "no match file",
                "list" => [],
                "start" => $start,
                "total" => $count_files];
        }
        $end = $start + $size;
        /** 获取指定范围的列表 */
        $list = [];
        $i_start = min($end, $count_files) - 1;
        for ($i = $i_start; $i < $count_files && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }
        return ["state" => "SUCCESS", "list" => $list,
            "start" => $start, "total" => $count_files];
    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param string $path
     * @param string $allowFiles
     * @param array $files
     * @return array|null
     */
    private function _getFiles(string $path, string $allowFiles, array &$files = []): ?array
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path_last = $path . $file;
                if (is_dir($path_last)) {
                    $this->_getfiles($path_last, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = array(
                            'url' => '/' . str_replace(PATH_ROOT, '', $path_last),
                            'mtime' => filemtime($path_last)
                        );
                    }
                }
            }
        }
        return $files;
    }

    protected function outByUEditor($result)
    {
        header("Content-type:application/json; charset=UTF-8");
        die(JSON::EnCode($result));
//        if ($callback = request()->get('callback')) {
//            if (preg_match("/^[\w_]+$/", $callback)) {
//                header("Content-Type: text/html; charset=utf-8");
//                exit(htmlspecialchars($callback) . '(' . JSON::EnCode($result) . ')');
//            } else {
//                $this->json([
//                    'state' => 'The callback parameter is invalid'
//                ]);
//            }
//        } else {
//            $this->json($result);
//        }
    }

}